/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.admin.freemarker.method;

import vip.dexian.common.utils.FreeMarkerUtils;
import vip.dexian.common.utils.NumberUtils;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * 货币格式化
 *
 * @author 挺好的 2023年05月30日 15:53
 */
@Component ("currencyMethod")
public class CurrencyMethod implements TemplateMethodModelEx {

    private static final String CURRENCY_SIGN = "¥";

    private static final String CURRENCY_UNIT = "元";

    @Override
    @SuppressWarnings ("rawtypes")
    public Object exec (List arguments) throws TemplateModelException {
        BigDecimal amount = FreeMarkerUtils.getArgument(0, BigDecimal.class, arguments);
        Boolean showSign = FreeMarkerUtils.getArgument(1, Boolean.class, arguments);
        Boolean showUnit = FreeMarkerUtils.getArgument(2, Boolean.class, arguments);
        if (amount != null) {

            String price = NumberUtils.setScale(amount).toString();

            if (showSign != null && showSign) {
                price = CurrencyMethod.CURRENCY_SIGN + price;
            }
            if (showUnit != null && showUnit) {
                price += CurrencyMethod.CURRENCY_UNIT;
            }
            return new SimpleScalar(price);
        }
        return null;
    }

}
